/*
 * Copyright 2017 Zhihu Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.xiaoyu.media.matisse.internal.ui

import android.app.Activity
import android.database.Cursor
import android.os.Bundle
import androidx.viewpager.widget.ViewPager
import androidx.appcompat.app.AppCompatDelegate
import com.xiaoyu.media.matisse.internal.entity.Album
import com.xiaoyu.media.matisse.internal.entity.Item
import com.xiaoyu.media.matisse.internal.entity.SelectionSpec
import com.xiaoyu.media.matisse.internal.model.AlbumMediaCollection
import com.xiaoyu.media.matisse.internal.ui.adapter.PreviewPagerAdapter
import java.util.*

class AlbumPreviewActivity : BasePreviewActivity(), AlbumMediaCollection.AlbumMediaCallbacks {

    private val mCollection = AlbumMediaCollection()
    private var mAlbum: Album? = null

    private var mIsAlreadySetPosition: Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (!SelectionSpec.instance.hasInited) {
            setResult(Activity.RESULT_CANCELED)
            finish()
            return
        }
        mCollection.onCreate(this, this)
        mCollection.load(mAlbum)

        changeCheckViewState(mPreviewItem)
    }

    override fun onDestroy() {
        super.onDestroy()
        mCollection.onDestroy()
    }

    override fun onAlbumMediaLoad(cursor: Cursor) {
        val items = ArrayList<Item>()
        while (cursor.moveToNext()) {
            cursor.let { Item.valueOf(cursor)?.let { it1 -> items.add(it1) } }
        }
        //        cursor.close();

        if (items.isEmpty()) {
            return
        }

        val adapter = mPager?.adapter as PreviewPagerAdapter?
        adapter?.addAll(items)
        adapter?.notifyDataSetChanged()
        if (!mIsAlreadySetPosition) {
            //onAlbumMediaLoad is called many times..
            mIsAlreadySetPosition = true
            val selected = intent.getParcelableExtra<Item>(EXTRA_ITEM)
            val selectedIndex = items.indexOf(selected)
            mPager?.setCurrentItem(selectedIndex, false)
            mPager?.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
                override fun onPageSelected(position: Int) {
                    changeCheckViewState(items[position])
                }
            })
            mPreviousPos = selectedIndex
        }
    }

    override fun onAlbumMediaReset() {
    }

    override fun initData(savedInstanceState: Bundle?) {
        super.initData(savedInstanceState)
        mAlbum = intent.getParcelableExtra(EXTRA_ALBUM)
        mPreviewItem = intent.getParcelableExtra(EXTRA_ITEM)
    }

    private fun changeCheckViewState(item: Item?) {
        mPreviewItem = null

        item?.let {
            if (SelectionSpec.instance.isLongVideo(it)) {
                mCheckView?.isEnabled = false
                mCheckView?.isChecked = false
                mCheckView?.alpha = 0.5f
            } else {
                mCheckView?.isEnabled = true
                mCheckView?.isChecked = mSelectedCollection.isSelected(it)
                mCheckView?.alpha = 1f
                updatePreviewItem(it);
            }
        }
    }

    private fun updatePreviewItem(item: Item) {
        if (assertAddPreviewedSelection(item)) {
            mPreviewItem = item
        }
    }

    private fun assertAddPreviewedSelection(item: Item): Boolean {
        val cause = mSelectedCollection.isPreviewAcceptable(item)
        return cause == null
    }

    companion object {

        const val EXTRA_ALBUM = "extra_album"
        const val EXTRA_ITEM = "extra_item"

        init {
            AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
        }
    }
}
